﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ_Service.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQ_Service.Services
{
    public class RabbitMQSendMsg
    {
        public RabbitMQSendConfig config { get; set; }

        public static IConnection conn;

        public RabbitMQSendMsg(RabbitMQSendConfig _config)
        {
            this.config = _config;
        }
        public IConnection GetConnection()
        {
            if (conn==null)
            {
                conn = RabbitMQBaseService.GetConnection(this.config.IP,this.config.Port,this.config.UserName,this.config.UserPwd,this.config.VirtualHost,60);
                
            }
            return conn;
        }
        public bool Send<T>(T message)
        {
            string value = JsonConvert.SerializeObject(message);
            return this.Send(value);
        }
        public bool Send(string msg)
        {
            if (string.IsNullOrWhiteSpace(msg))
            {
                return false;
            }
            try
            {
                using (var channel=this.GetConnection().CreateModel())
                {
                    if (!string.IsNullOrWhiteSpace(this.config.ExchangeName))
                    {
                        channel.ExchangeDeclare(this.config.ExchangeName, this.config.ExchangeType.ToString(), this.config.DurableQueue, false, null);
                    }
                    else
                    {
                        channel.QueueDeclare(this.config.QueueName, this.config.DurableQueue, false, false, null);
                    }

                    IBasicProperties properties = channel.CreateBasicProperties();
                    properties.DeliveryMode = Convert.ToByte(this.config.DurableMsg ? 2 : 1); //支持持久化数据

                    byte[] data = Encoding.UTF8.GetBytes(msg);

                    if (string.IsNullOrEmpty(this.config.ExchangeName))
                    {
                        channel.BasicPublish("", this.config.QueueName, properties, data);
                    }
                    else
                    {
                        channel.BasicPublish(this.config.ExchangeName, this.config.RoutingKey, properties, data);
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
